package com.sunshuo.springsecuritydemo.service;

import com.sunshuo.springsecuritydemo.pojo.User;
import com.sunshuo.springsecuritydemo.pojo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName UserDetailService
 * @Description
 * @Author sunshuo
 * @Date 2021/11/6 20:22
 */
@Service
public class UserDetailService implements UserDetailsService {

    private UserService userService;

    private RoleService roleService;

    private MenuService menuService;

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

    @Autowired
    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库查询用户信息
        User user = userService.findUserByUsername(username);
        if (user != null) {
            // 查询用户角色
            List<String> roleNames = roleService.getRoleNameByUserId(user.getId());
            List<String> roleCodes = roleNames.stream().map(roleName -> {
                return "ROLE_" + roleName;
            }).collect(Collectors.toList());
            // 查询角色权限码
            List<String> authCodes = menuService.getAuthCodeByRoleNames(roleNames);
            roleCodes.addAll(authCodes);
            // 设置用户权限列表
            user.setGrantedAuthorityList((AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",",roleCodes))));
        }
        return user;
    }
}
